//
//  XMRecentPhotosListViewController.m
//  XunMi
//
//  Created by MacBook on 2024/3/22.
//  Copyright © 2024 TieZhu. All rights reserved.
//

#import "XMRecentPhotosListViewController.h"
#import "XMRecentPhotosUploadViewController.h"
#import "XMRecentPhotosListCell.h"
#import "XMRecentPhotosModel.h"
#import <YBImageBrowser/YBImageBrowser.h>

@interface XMRecentPhotosListViewController ()<UICollectionViewDataSource, UICollectionViewDataSource>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray <XMRecentPhotosModel *> *dataArray;
@property (nonatomic, assign) NSInteger pageNo;
@end

@implementation XMRecentPhotosListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initVariables];
    [self setupSubviews];
    [self initData];
}

#pragma mark - 初始化变量
- (void)initVariables {
    self.pageNo = 1;
    [kNotificationCenter addObserver:self selector:@selector(refreshData) name:@"photoListRefresh" object:nil];
}

- (void)refreshData {
    self.pageNo = 1;
    [self.dataArray removeAllObjects];
    [self initData];
}

- (void)initData {
    [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
    NSMutableDictionary *dic = @{
        @"pageNo":@(self.pageNo),
        @"page_size":@(10)
    }.mutableCopy;
    
    if (![XMUtil isBlankString:self.userId]) {
        [dic setObject:self.userId forKey:@"see_user_id"];
    }
    [YHNetworkManager.sharedInstance postWithUrl:@"api/album/obtain" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            [self.collectionView hideStatusView];
            [MBProgressHUD hideHUD];
            [self.dataArray addObjectsFromArray:[XMRecentPhotosModel mj_objectArrayWithKeyValuesArray:[result safe_objectForKey:@"record"]]];
            if (self.dataArray.count == 0) {
                [self.collectionView showStatusView:YHViewStatusTypeEmptyData spacing:0 retryBlock:nil];
                self.collectionView.statusTitleLabel.text = @"还没有近期照片哦~";
            }
        }
        [self.collectionView reloadData];
    }];
}

#pragma mark - setupSubViews
- (void)setupSubviews {
    [self.navLeft2Btn setTitle:@"近期照片" forState:UIControlStateNormal];
    [self.navRightBtn setTitle:@"上传" forState:UIControlStateNormal];
    [self.navRightBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(66, 32));
    }];
    [self.navRightBtn setBackgroundColor:kAppMainColor];
    [self.navRightBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [self.navRightBtn addTarget:self action:@selector(upload) forControlEvents:UIControlEventTouchUpInside];
    kCornerRadius(self.navRightBtn, 16, 0, UIColor.clearColor);
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake((kScreenWidth - 60) / 3, (kScreenWidth - 60) / 3);
    flowLayout.minimumLineSpacing = 10;
    flowLayout.minimumInteritemSpacing = 10;
    [self.collectionView setCollectionViewLayout:flowLayout];
    
    [self.collectionView registerNib:kNibWithName(kStringFromClass(XMRecentPhotosListCell)) forCellWithReuseIdentifier:kStringFromClass(XMRecentPhotosListCell)];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XMRecentPhotosListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kStringFromClass(XMRecentPhotosListCell) forIndexPath:indexPath];
    cell.model = [self.dataArray safe_objectAtIndex:indexPath.item];
    
    XMWeakSelf(self);
    cell.longPressBlock = ^(XMRecentPhotosListCell * _Nonnull cell, XMRecentPhotosModel * _Nonnull model) {
        XMStrongSelf(self);
        [XMAlertHelper alertTitle:@"确定删除?" message:nil cancelTitle:@"取消" sureTitle:@"确定" cancelAction:^{
        } sureAction:^{
            [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
            NSMutableDictionary *dic = @{
                @"index":model.xmId
            }.mutableCopy;
            [YHNetworkManager.sharedInstance postWithUrl:@"api/album/delete" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
                if (tip.success) {
                    [MBProgressHUD hideHUD];
                    [self.dataArray removeObject:model];
                    [self.collectionView reloadData];
                    if (self.dataArray.count == 0) {
                        [self.collectionView showStatusView:YHViewStatusTypeEmptyData spacing:0 retryBlock:nil];
                        self.collectionView.statusTitleLabel.text = @"还没有近期照片哦~";
                    }
                }
            }];
        }];
    };
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    XMRecentPhotosListCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    __block NSMutableArray *datas = [NSMutableArray array];
    [self.dataArray enumerateObjectsUsingBlock:^(XMRecentPhotosModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        // 网络图片
        YBIBImageData *data = [YBIBImageData new];
        data.imageURL = [NSURL URLWithString:obj.image.file_url];
        data.projectiveView = cell.imgV;
        [datas addObject:data];
    }];
    
    YBImageBrowser *browser = [YBImageBrowser new];
    browser.dataSourceArray = datas;
    browser.currentPage = indexPath.item;
    [browser show];
}

#pragma mark - viewBlock
- (void)viewBlock {
    
}
#pragma mark - Actions
- (void)upload {
    if (self.dataArray.count == 9) {
        [MBProgressHUD showHUDMsg:@"最多只能添加9张照片,请先删除再上传!" toView:nil];
        return;
    }
    XMRecentPhotosUploadViewController *vc = [[XMRecentPhotosUploadViewController alloc] initWithNibName:kStringFromClass(XMRecentPhotosUploadViewController) bundle:nil];
    vc.count = self.dataArray.count;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - Public Methods
#pragma mark - Privacy Methods

#pragma mark - lazy
- (NSMutableArray<XMRecentPhotosModel *> *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)dealloc {
    NSLog(@"释放了%@",[self class]);
    [kNotificationCenter removeObserver:self];
    //    NSLog(@"释放了 -[%@ %s]",NSStringFromClass([self class]), sel_getName(_cmd));
}
@end
